package org.akomantoso.core.data;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.akomantoso.core.data.attribute.Source;
import org.akomantoso.core.io.Externalizable;
import org.akomantoso.core.io.Input;
import org.akomantoso.core.io.Output;
import org.akomantoso.core.io.OutputUtil;
import org.akomantoso.core.io.util.RefItemUtil;

/**
 * The attribute source links to the agent (person, organization) providing the specific annotation or markup
 * 
 * <pre>
 * 	<xsd:element name="references">
 * 		<xsd:complexType>
 * 			<xsd:sequence minOccurs="1" maxOccurs="unbounded">
 * 				<xsd:group ref="refItems"/>
 * 			</xsd:sequence>
 * 			<xsd:attributeGroup ref="source"/>
 * 		</xsd:complexType>
 * 	</xsd:element>
 * </pre>
 * 
 * @author <a href="mailto:jacques.militello@gmail.com">Jacques Militello</a>
 * 
 * @since http://www.akomantoso.org/1.0
 */
public final class References implements Source, Externalizable {

	public static final String ELEMENT = "references";

	// Mandatory
	private String _source;

	// Mandatory (min 1)
	private final List<RefItem> _refItems = new ArrayList<RefItem>(4);

	/**
	 * @see org.akomantoso.core.data.attribute.Source#getSource()
	 */
	public String getSource() {
		return _source;
	}

	/**
	 * @see org.akomantoso.core.data.attribute.Source#setSource(java.lang.String)
	 */
	public void setSource(String source) {
		_source = source;
	}

	/**
	 * @return the refItems
	 */
	public List<RefItem> getRefItems() {
		return _refItems;
	}

	public void addRefItem(RefItem refItem) {
		_refItems.add(refItem);
	}

	/**
	 * @see org.akomantoso.core.io.Externalizable#writeExternal(org.akomantoso.core.io.Output)
	 */
	public <T extends Output> void writeExternal(T out) throws IOException {
		out.writeStart(ELEMENT);
		OutputUtil.writeSource(out, this);
		for (int i = 0, n = _refItems.size(); i < n; i++) {
			_refItems.get(i).writeExternal(out);
		}
		out.writeEnd();
	}

	/**
	 * @see org.akomantoso.core.io.Externalizable#readExternal(org.akomantoso.core.io.Input)
	 */
	public <T extends Input> void readExternal(T in) throws IOException {
		_source = in.readAttribute(Source.ATTRIBUTE);
		RefItemUtil.read(in, _refItems);
	}

}